package net.wofly.right.service.impl;

import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.util.Identities;
import net.wofly.common.util.PageHelper;
import net.wofly.common.util.ResultCode;
import net.wofly.common.util.ReturnBean;
import net.wofly.right.domain.*;
import net.wofly.right.repository.RightConfigRepository;
import net.wofly.right.repository.RoleRepository;
import net.wofly.right.service.*;
import net.wofly.sale.stock.util.WarehouseType;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("iRoleService")
@Transactional
public class RoleServiceImpl implements IRoleService {

	public static final String CACHE_NAME = "role";

	@Autowired
	RoleRepository roleRepository;
	@Autowired
	IUserService iUserService;
	@Autowired
	IUserRoleService iUserRoleService;
	@Autowired
	IFuncListService iFuncListService;
	@Autowired
	IRightConfigService iRightConfigService;
	@Autowired
	IOrganizationService iOrganizationService;
	@Autowired
    RightConfigRepository rightConfigRepository;

	@Override
	@CachePut(value = CACHE_NAME, key = "#entity.roleID")
	public Role save(Role entity) {
		return roleRepository.save(entity);
	}

	@Override
	@CacheEvict(value = CACHE_NAME, key = "#entity.roleID", beforeInvocation = true)
	public void delete(Role entity) {
		roleRepository.delete(entity);
	}

	@Override
	@CacheEvict(value = CACHE_NAME, key = "#key", beforeInvocation = true)
	public void delete(String key) {
		roleRepository.delete(key);
	}

	@Override
	@Cacheable(value = CACHE_NAME, key = "#key")
	public Role findOne(String key) {
		return roleRepository.findOne(key);
	}

	@Override
	public List<Role> save(List<Role> entityList) {
		return (List<Role>) roleRepository.save(entityList);
	}

	@Override
	public ReturnBean<List<Role>> getCustomType() {
		List<Role> roles = roleRepository.findCustomType("200") ; 
		return  new ReturnBean<>(ResultCode.SUCCESS, "查询成功", roles);
	}

	@Override
	public ReturnBean<List<Role>> getAllRole() {
		List<Role> roleList = roleRepository.findByStatus(1);
		for(Role role:roleList) {
			if (role.getWarehouseFlag().equals(1)) {
				role.setWarehouseFlagStr("有");
			}else {
				role.setWarehouseFlagStr("无");
			}
			
			if(role.getWarehouseType().equals(0)) {
				role.setWarehouseTypeStr("");
			}else {
				role.setWarehouseTypeStr(WarehouseType.getName(role.getWarehouseType()));
			}
		}
		return new ReturnBean<>(ResultCode.SUCCESS, "获取角色列表成功", roleList);
	}

	@Override
	public ReturnBean<Role> saveRole(String roleID, String roleName, Integer warehouseFlag, Integer warehouseType) {
		Role role;
		String msg;
		if (StringUtils.isBlank(roleID)) {
			role = new Role();
			role.setRoleID(Identities.uuid2());
			role.setStatus(1);
			msg = "添加角色成功!";
		} else {
			role = roleRepository.findOne(roleID);
			if (null == role) {
				return new ReturnBean<>(ResultCode.ERROR_SERVICE, "未找到此角色！");
			}
			role.setModifyDate(System.currentTimeMillis());
			msg = "修改角色成功!";
		}

		role.setModifyDate(System.currentTimeMillis());

		role.setRoleName(roleName);
		role.setWarehouseFlag(warehouseFlag);
		role.setWarehouseType(warehouseType);

		return new ReturnBean<>(ResultCode.SUCCESS, msg, roleRepository.save(role));
	}

	@Override
	public ReturnBean<PageWrapper<User>> getUserByRoleID(String roleID, Integer pageNum, Integer pageSize) {
		Role role = findOne(roleID);
		if (role == null) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "角色ID不正确，未获取到角色！");
		}

		Pageable pageable = new PageRequest(pageNum - 1, pageSize);
		Page<User> userPage = iUserRoleService.findPageByRoleID(roleID, pageable);
		userPage.getContent().stream().filter(user -> StringUtils.isNotBlank(user.getOrganizationID())).forEach(user -> {
			Organization organization = iOrganizationService.findOne(user.getOrganizationID());
			if (organization != null) {
				user.setOrganizationName(organization.getOrganizationName());
			}
		});

		return new ReturnBean<>(ResultCode.SUCCESS, "获取角色下人员列表成功", PageHelper.toPage(userPage));
	}

	@Override
	public ReturnBean<PageWrapper<FuncList>> getFuncListByRoleID(String roleID, Integer funcType, Integer pageNum, Integer pageSize) {
		Role role = findOne(roleID);
		if (role == null) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "角色ID不正确，未获取到角色！");
		}

		Pageable pageable = new PageRequest(pageNum - 1, pageSize);
		Page<FuncList> funcListPage = iFuncListService.findPageByFuncType(funcType, pageable);
		List<RightConfig> rightConfigs = iRightConfigService.findByRoleID(roleID);
		Map<String, RightConfig> rightConfigMap = new HashMap<>(rightConfigs.size());
		for (RightConfig rightConfig : rightConfigs) {
			rightConfigMap.put(rightConfig.getFuncListID(), rightConfig);
		}

		for (FuncList funcList : funcListPage.getContent()) {
			RightConfig rightConfig = rightConfigMap.get(funcList.getFuncListID());
			if (rightConfig != null && rightConfig.getRightStatus() == 1) {
				funcList.setRightStatus(1);
				funcList.setRightConfigID(rightConfig.getRightConfigID());
			} else {
				funcList.setRightStatus(0);
			}
		}
		String msg = "根据角色ID获取接菜单功能列表成功！";
		if (funcType == 1) {
			msg = "根据角色ID获取接口功能列表成功！";
		}
		return new ReturnBean<>(ResultCode.SUCCESS, msg, PageHelper.toPage(funcListPage));
	}

	@Override
	public ReturnBean<RightConfig> addRightConfig(String roleID, String funcListID) {
		List<RightConfig> rightConfigs = iRightConfigService.findByRoleIDAndFuncListID(roleID, funcListID);
		RightConfig rightConfig;
		if (rightConfigs.size() > 0) {
			rightConfig = rightConfigs.get(0);
			rightConfig.setRightStatus(1);
		} else {
			rightConfig = new RightConfig();
			rightConfig.setFuncListID(funcListID);
			rightConfig.setModifyDate(System.currentTimeMillis());
			rightConfig.setRightConfigID(Identities.uuid2());
			rightConfig.setRightStatus(1);
			rightConfig.setRoleID(roleID);
		}
		return new ReturnBean<>(ResultCode.SUCCESS, "添加角色功能关系成功！", iRightConfigService.save(rightConfig));
	}

	@Override
	public ReturnBean<RightConfig> removeRightConfig(String roleID, String funcListID) {
		List<RightConfig> rightConfigs = iRightConfigService.findByRoleIDAndFuncListID(roleID, funcListID);
		RightConfig rightConfig;
		if (rightConfigs.size() > 0) {
			rightConfig = rightConfigs.get(0);
			rightConfig.setRightStatus(1);
			return new ReturnBean<>(ResultCode.SUCCESS, "删除角色功能关系成功！", iRightConfigService.save(rightConfig));
		} else {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "未找到对应的关系，删除角色功能关系失败！");
		}
	}

	@Override
	public ReturnBean<String> addRightConfigList(List<RightConfig> rightConfigs) {
		Long exeTime = System.currentTimeMillis();
		RightConfig dbRightConfig =  null ;
		for (RightConfig rightConfig:rightConfigs) {
			dbRightConfig = getDBRightConfig(rightConfig) ;
			if (null==dbRightConfig) {
				rightConfig.setRightConfigID(Identities.uuid2());
				rightConfig.setRightStatus(1);
				rightConfig.setModifyDate(exeTime);
				
			}else {
				rightConfig.setRightConfigID(dbRightConfig.getRightConfigID());
				rightConfig.setRightStatus(1);
				rightConfig.setModifyDate(exeTime);
			}
		}
		
		rightConfigRepository.save(rightConfigs) ;
		
		return new ReturnBean<>(ResultCode.SUCCESS, "批量添加角色功能关系成功！");
	}
	
	private RightConfig getDBRightConfig(RightConfig rightConfig) {
		RightConfig dbRightConfig =  null ;
		List<RightConfig> rightConfigs = iRightConfigService.findByRoleIDAndFuncListID(rightConfig.getRoleID(), rightConfig.getFuncListID());
		
		if (rightConfigs.size() > 0) {
			dbRightConfig = rightConfigs.get(0);
		} 
		
		return dbRightConfig ;
	}

	@Override
	public ReturnBean<String> removeRightConfigList(List<String> rightConfigIDs) {
		Iterable<RightConfig> rightConfigs = rightConfigRepository.findAll(rightConfigIDs) ;
		
		if (null == rightConfigs) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "未找到对应的关系，删除角色功能关系失败！");
		}
		
		rightConfigRepository.delete(rightConfigs) ;
		
		return new ReturnBean<>(ResultCode.SUCCESS, "批量删除角色功能关系成功！");
	}
}
